const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const { convertToPDF, convertToWord } = require('../controllers/convertController');

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../../uploads'));
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 50 * 1024 * 1024, // 限制50MB
    files: 1
  },
  fileFilter: function (req, file, cb) {
    const ext = path.extname(file.originalname).toLowerCase();
    if (req.path === '/word2pdf' && ext !== '.doc' && ext !== '.docx') {
      return cb(new Error('只支持.doc和.docx格式文件'));
    }
    if (req.path === '/pdf2word' && ext !== '.pdf') {
      return cb(new Error('只支持.pdf格式文件'));
    }
    cb(null, true);
  }
});

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads');
if (!require('fs').existsSync(uploadDir)) {
  require('fs').mkdirSync(uploadDir, { recursive: true });
}

// 文件转换路由
router.post('/convert', upload.single('file'), convertToPDF);

// Word转PDF路由
router.post('/word2pdf', upload.single('file'), convertToPDF);

// PDF转Word路由
router.post('/pdf2word', upload.single('file'), convertToWord);

module.exports = router; 